<template>
  <div class="search-history">
    <van-cell-group class="cell-list">
      <van-cell title="历史记录">
        <van-icon
          v-if="!isCloseBtnShow"
          slot="default"
          name="delete-o"
          @click="handleShowClose"
        />
        <div v-else slot="default">
          <span class="delete-all"
            @click="deleteConfirm">全部删除</span>
          <span class="delete-finish"
            @click="handleShowClose"
          >完成</span>
        </div>
      </van-cell>
      <van-cell
        v-for="(item, index) in searchHistories"
        :key="index"
        :title="item"
      >
        <van-icon
          v-show="isCloseBtnShow"
          slot="default"
          name="close"
          @click="$emit('deleteSingleHistory', index)"
        />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { Dialog } from 'vant'
export default {
  name: 'SearchHistory',
  components: {
    [Dialog.Component.name]: Dialog.Component
  },
  props: {
    searchHistories: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      isCloseBtnShow: false // 控制关闭按钮的展示
    }
  },
  watch: {
    searchHistories: {
      handler () {
        if (!this.searchHistories.length) {
          this.isCloseBtnShow = false
        }
      }
    }
  },
  methods: {
    handleShowClose () {
      if (this.searchHistories.length) { // 列表有东西才显示close
        this.isCloseBtnShow = !this.isCloseBtnShow
      } else {
        this.$toast('历史记录为空')
      }
    },
    deleteConfirm () {
      Dialog.confirm({
        title: '确认清空历史记录？'
        // message: '弹窗内容'
      })
        .then(() => {
          this.$emit('deleteAllHistories')
          this.$toast.success('清空历史记录成功')
          this.isCloseBtnShow = false
        })
        .catch(() => {
        })
    }
  }
}
</script>

<style scoped lang="less">
  /deep/ .cell-list {
    margin-top: 10px;
    .van-icon {
      font-size: 30px;
    }
    .delete-all {
      margin-right: 20px;
    }
  }
</style>
